package com.wnnight.wys.security;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class JwtUtils {
    @Autowired
    private JWTProperties jwtProperties;

    public String creatJWT(int id, String account, int roleId) {
        DateTime now = DateTime.now();
        DateTime newTime = now.offsetNew(DateField.SECOND, jwtProperties.getExpireSeconds());
        Map<String, Object> payload = new HashMap<>();
        //签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        //过期时间
        payload.put(JWTPayload.EXPIRES_AT, newTime);
        //生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);
        //载荷
        payload.put("id", id);
        payload.put("account", account);
        payload.put("roleId", roleId);
        String token = JWTUtil.createToken(payload, jwtProperties.getSecret().getBytes());
        return token;
    }

    public String getUUID() {
        String s = UUID.randomUUID().toString().replace("-", "");
        return s;
    }

    //校验
    public boolean verifyJWT(String token) {
        JWT jwt = JWTUtil.parseToken(token);

        boolean verifyKey = jwt.setKey(jwtProperties.getSecret().getBytes()).verify();

        boolean verifyTime = jwt.validate(0);

        return verifyKey && verifyTime;
    }

    //取值
    public static Object getInfo(String jwt, String name) {
        JWT token = JWTUtil.parseToken(jwt);
        return token.getPayload(name);
    }
}
